import {request} from "../../request/index.js";
import * as asyncWx from "../../utils/asyncWx.js";
Page({
    data:{
        goodsObj:{},
        isCollect:false
    },
    //全局商品对象
    GoodsObj:{},
    // onLoad(options){
    //     this.getGoodsDetailData(options.goods_id);
    // },
    onShow(){
        const page=getCurrentPages();
        const currentPage=page[page.length-1];
        const {goods_id}=currentPage.options;
        this.getGoodsDetailData(goods_id);
    },
    //获取商品请求数据事件监听
    async getGoodsDetailData(goods_id){
        let res=await request({
            url:"/goods/detail",
            data:{
                goods_id
            }
        });
        this.GoodsObj=res.data.message;
        const collect=wx.getStorageSync("collect") || [];
        let isCollect=collect.some((item)=>{
            return item.goods_id===this.GoodsObj.goods_id;
        });
        this.setData({
            goodsObj:{
                goods_name:res.data.message.goods_name,
                goods_introduce:res.data.message.goods_introduce.replace(/\.webp/g,".jpg"),
                goods_price:res.data.message.goods_price,
                pics:res.data.message.pics,
            },
            isCollect
        });
    },
    //点击方法预览轮播图照片事件监听
    handlePreviewImage(e){
        const urls=this.GoodsObj.pics.map((item)=>{
            return item.pics_mid;
        });
        wx.previewImage({
            current:e.currentTarget.dataset.url,
            urls
        });
    },
    //点击加入购物车功能事件监听
    handleJoinCart(){
        let carts=wx.getStorageSync("carts") || [];
        let index=carts.findIndex((item)=>{
            return item.goods_id===this.GoodsObj.goods_id;
        });
        if(index===-1){//购物车没有此商品，则加入购物车
            carts.push(this.GoodsObj);
            this.GoodsObj.num=1;
            this.GoodsObj.checked=true;
        }else{//购物车里面已经有此商品，则商品数量++
            carts[index].num++;
        };
        wx.setStorageSync("carts",carts);
        wx.showToast({
            title:"加入成功",
            icon:"success",
            mask:true
        });
    },
    //点击收藏按钮事件监听
    async handleCollect(){
        let isCollect=false;
        let collect=wx.getStorageSync("collect") || [];
        const index=collect.findIndex((item)=>{
            return item.goods_id===this.GoodsObj.goods_id;
        });
        if(index===-1){
            collect.push(this.GoodsObj);
            isCollect=true;
            await asyncWx.showToast({
                title:"收藏成功",
                icon:"success",
                mask:true
            });
        }else{
            collect.splice(index,1);
            isCollect=false;
            await asyncWx.showToast({
                title:"取消收藏",
                icon:"success",
                mask:true
            });
        };
        this.setData({isCollect});
        wx.setStorageSync("collect",collect);
    }
});